Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Reactjs Interview Questions Description: React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side
Questions Core React What is React? What are the major features of React? What is JSX? What is the difference between Element and Component? How to create components in React? When to use a Class Component over a Function Component? What are Pure Components? What is state in React? What are props in React? What is the difference between state and props? Why should we not update the state directly? What is the purpose of callback function as an argument of setState()? What is the difference between HTML and React event handling? How to bind methods or event handlers in JSX callbacks? How to pass a parameter to an event handler or callback? What are synthetic events in React? What are inline conditional expressions? What is “key” prop and what is the benefit of using it in arrays of elements? What is the use of refs? How to create refs? What are forward refs? 1
No
...
Questions
60 61 62 63 64 65
How to use InnerHtml in React? How to use styles in React? How events are different in React? What will happen if you use setState in constructor? What is the impact of indexes as keys? Is it good to use setState() in componentWillMount() method? What will happen if you use props in initial state? How do you conditionally render components? Why we need to be careful when spreading props on DOM elements?? How you use decorators in React? How do you memoize a component? How you implement Server-Side Rendering or SSR? How to enable production mode in React? What is CRA and its benefits? What is the lifecycle methods order in mounting? What are the lifecycle methods going to be deprecated in React v16? What is the purpose of getDerivedStateFromProps() lifecycle method? What is the purpose of getSnapshotBeforeUpdate() lifecycle method? Do Hooks replace render props and higher order components? What is the recommended way for naming components? What is the recommended ordering of methods in component class? What is a switching component? Why we need to pass a function to setState()? What is strict mode in React? What are React Mixins? Why is isMounted() an anti-pattern and what is the proper solution? What are the Pointer Events supported in React? Why should component names start with capital letter? Are custom DOM attributes supported in React v16? What is the difference between constructor and getInitialState? Can you force a component to re-render without calling setState? What is the difference between super() and super(props) in React using ES6 classes? How to loop inside JSX?
Questions React Router What is React Router? How React Router is different from history library? What are the components of React Router v4? What is the purpose of push and replace methods of history? How do you programmatically navigate using React router v4? How to get query parameters in React Router v4 Why you get “Router may have only one child element” warning? How to pass params to history
...
Questions
162 163 164
How to use connect from React Redux? How to reset state in Redux? Whats the purpose of at symbol in the redux connect decorator? What is the difference between React context and React Redux? Why are Redux state functions called reducers? How to make AJAX request in Redux? Should I keep all component’s state in Redux store? What is the proper way to access Redux store? What is the difference between component and container in React Redux? What is the purpose of the constants in Redux? What are the different ways to write mapDispatchToProps()? What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()? How to structure Redux top level directories? What is redux-saga? What is the mental model of redux-saga? What are the differences between call and put in redux-saga What is Redux Thunk? What are the differences between redux-saga and redux-thunk What is Redux DevTools? What are the features of Redux DevTools? What are Redux selectors and Why to use them? What is Redux Form? What are the main features of Redux Form? How to add multiple middlewares to Redux? How to set initial state in Redux? How Relay is different from Redux? What is an action in Redux? React Native What is the difference between React Native and React? How to test React Native apps? How to do logging in React Native? How to debug your React Native? React supported libraries and Integration What is reselect and how it works? What is Flow? What is the difference between Flow and PropTypes?
No
...
js? What is the difference between React and Angular? Why React tab is not showing up in DevTools? What are styled components? Give an example of Styled Components? What is Relay? How to use TypeScript in create-react-app application? Miscellaneous What are the main features of reselect library? Give an example of reselect usage? Does the statics object work with ES6 classes in React? Can Redux only be used with React? Do you need to have a particular build tool to use Redux? How Redux Form initialValues get updated from state? How React PropTypes allow different type for one prop? Can I import an SVG file as react component? Why are inline ref callbacks or functions not recommended? What is render hijacking in React? What are HOC factory implementations? How to pass numbers to React component? Do I need to keep all my state into Redux? Should I ever use react internal state? What is the purpose of registerServiceWorker in React? What is React memo function? What is React lazy function? How to prevent unnecessary updates using setState? How do you render Array, Strings and Numbers in React 16 Version? How to use class field declarations syntax in React classes? What are hooks? What rules need to be followed for hooks? How to ensure hooks followed the rules in your project? What are the differences between Flux and Redux? What are the benefits of React Router V4? Can you describe about componentDidCatch lifecycle method signature?
What are the conditions to safely use the index as a key? Is it keys should be globally unique? What is the popular choice for form handling? What are the advantages of formik over redux form library? Why do you not required to use inheritance? Can I use web components in react application? What is dynamic import? What are loadable components? What is suspense component? What is route based code splitting? Give an example on How to use context? What is the purpose of default value in context? How do you use contextType? What is a consumer? How do you solve performance corner cases while using context? What is the purpose of forward ref in HOCs? Is it ref argument available for all functions or class components? Why do you need additional care for component libraries while using forward refs? How to create react class components without ES6? Is it possible to use react without JSX? What is diffing algorithm? What are the rules covered by diffing algorithm? When do you need to use refs? Is it prop must be named as render for render props? What are the problems of using render props with pure components? How do you create HOC using render props? What is windowing technique? How do you print falsy values in JSX? What is the typical use case of portals? How do you set default value for uncontrolled component? What is your favorite React stack? What is the difference between Real DOM and Virtual DOM? How to add Bootstrap to a react application? Can you list down top websites or applications using react as front end framework? Is it recommended to use CSS In JS technique in React?
No
...
9? What is the purpose of eslint plugin for hooks? What is the difference between Imperative and Declarative in React? What are the benefits of using typescript with reactjs? How do you make sure that user remains authenticated on page refresh while using Context API State Management? What are the benefits of new JSX transform? How does new JSX transform different from old transform? How do you get redux scaffolding using create-react-app? What are React Server components? What is prop drilling? What is state mutation and how to prevent it? What is the difference between useState and useRef hook?
Core React 1
...
It is used for handling view layer for web and mobile apps
...
React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012
...
What are the major features of React? The major features of React are: • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive
...
• Follows Unidirectional data flow or data binding
...
� Back to Top 3
...
Basically it just provides syntactic sugar for the React
...
In the example below text inside
tag is returned as JavaScript function to the render function
...
Component { render() { return(
{'Welcome to React world!'}
) } } � Back to Top 4
...
Elements can 11
contain other Elements in their props
...
Once an element is created, it is never mutated
...
createElement( 'div', {id: 'login-btn'}, 'Login' ) The above React
...
render():
Login
Whereas a component can be declared in several different ways
...
In either case, it takes props as an input, and returns a JSX tree as the output: const Button = ({ onLogin }) =>
Login
Then JSX gets transpiled to a React
...
createElement( 'div', { id: 'login-btn', onClick: onLogin }, 'Login' ) � Back to Top 5
...
1
...
Those are pure JavaScript functions that accept props object as the first parameter and return React elements:
12
“jsx harmony function Greeting({ message }) {
{Hello, ${message}‘}
return
} “‘ 2
...
The above function component can be written as: jsx harmony render() { } }
class Greeting extends React
...
props
...
When to use a Class Component over a Function Component? If the component needs state or lifecycle methods then use class component otherwise use function component
...
8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component
...
What are Pure Components? React
...
Component except that it handles the shouldComponentUpdate() method for you
...
Component on the other hand won’t compare current props and state to next out of the box
...
� Back to Top 8
...
We should always try to make our state as simple as possible and minimize the number of stateful components
...
Component { constructor(props) { super(props) this
...
state
...
e
...
� Back to Top 9
...
They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes
...
14
The primary purpose of props in React is to provide following component functionality: 1
...
2
...
3
...
props
...
For example, let us create an element with reactProp property: jsx harmony
This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which originally already exists on all components created using React library
...
reactProp � Back to Top 10
...
While both of them hold information that influences the output of render, they are different in their functionality with respect to component
...
� Back to Top 11
...
//Wrong this
...
message = 'Hello world' Instead use setState() method
...
When state changes, the component responds by rerendering
...
setState({ message: 'Hello World' }) Note: You can directly assign to the state object either in constructor or using latest javascript’s class field declaration syntax
...
What is the purpose of callback function as an argument of setState()? The callback function is invoked when setState finished and the component gets rendered
...
Note: It is recommended to use lifecycle method rather than this callback function
...
log('The name has updated and component re-ren � Back to Top 13
...
In HTML, the event name usually represents in lowercase as a convention:
{'Click
3
...
jsx harmony handleClick() { console
...
handleClick()}>Click Me; } Note: If the callback is passed as prop to child components, those components might do an extra re-rendering
...
bind() or public class fields syntax approach considering performance
...
How to pass a parameter to an event handler or callback? You can use an arrow function to wrap around an event handler and pass parameters:
17
jsx harmony this
...
bind: jsx harmony
...
bind(this, id)} /> Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function jsx harmony onClick={this
...
log("Hello, your ticket number is", id) }; � Back to Top 16
...
Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers
...
What are inline conditional expressions? You can use either if statements or ternary expressions which are available from JS to conditionally render expressions
...
jsx harmony
Hello!
{ !isLogin?
unread messages
...
messages
...
length} :
You
}
� Back to Top 18
...
Key prop helps React identify which items have changed, are added, or are removed
...
map((todo) => key={todo
...
text} ) 18
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort: jsx harmony const todoItems = todos
...
text} ) Note: 1
...
This can negatively impact performance and may cause issues with component state
...
If you extract list item as separate component then apply keys on list component instead of li tag
...
There will be a warning message in the console if the key prop is not present on list items
...
What is the use of refs? The ref is used to return a reference to the element
...
What is Redux Form? Redux Form works with React and Redux to enable a form in React to use Redux to store all of its state
...
� Back to Top 184
...
Field values persistence via Redux store
...
Validation (sync/async) and submission
...
Formatting, parsing and normalization of field values
...
How to add multiple middlewares to Redux? You can use applyMiddleware()
...
How to set initial state in Redux? You need to pass initial state as second argument to createStore: const rootReducer = combineReducers({ todos: todos, visibilityFilter: visibilityFilter }) const initialState = { todos: [{ id: 123, name: 'example', completed: false }] } const store = createStore( rootReducer, initialState ) � Back to Top 187
...
The main difference is that relay only manages state originated from the server, and all access to the state is used via GraphQL queries (for reading data) and mutations (for changing data)
...
188
...
They are the only source of information for the store
...
For example, let’s take an action which represents adding a new todo item: 92
{ type: ADD_TODO, text: 'Add todo item' } � Back to Top
React Native � Back to Top 188
...
React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use React to build your components, and implements React under the hood
...
How to test React Native apps? React Native can be tested only in mobile simulators like iOS and Android
...
io) Where it syncs using QR code, your mobile and computer should be in same wireless network
...
How to do logging in React Native? You can use console
...
warn, etc
...
29 you can simply run the following to see logs in the console: $ react-native log-ios $ react-native log-android � Back to Top 191
...
Run your application in the iOS simulator
...
Press Command + D and a webpage should open up at http://localhost:8081/debugger-ui
...
Enable Pause On Caught Exceptions for a better debugging experience
...
Press Command + Option + I to open the Chrome Developer tools, or open it via View -> Developer -> Developer Tools
...
You should now be able to debug as you normally would
...
What is reselect and how it works? Reselect is a selector library (for Redux) which uses memoization concept
...
Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes
...
It’s memoization and cache are fully customizable
...
What is Flow? Flow is a static type checker designed to find type errors in JavaScript
...
For example, Flow helps you catch errors involving null, unlike most type systems
...
What is the difference between Flow and PropTypes? Flow is a static analysis tool (static checker) which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time
...
It can’t check anything other than the types of the props being passed to a given component
...
� Back to Top 195
...
Install font-awesome: $ npm install --save font-awesome 2
...
js file: import 'font-awesome/css/font-awesome
...
css' 3
...
What is React Dev Tools? React Developer Tools let you inspect the component hierarchy, including component props and state
...
The official extensions available for different browsers or environments
...
Chrome extension 2
...
Standalone app (Safari, React Native, etc) � Back to Top 197
...
) then you must first open Chrome Extensions and check Allow access to file URLs
...
How to use Polymer in React? You need to follow below steps to use Polymer in React, 1
...
/bower_components/polymer/polymer
...
textContent = 'I am a calender' } }) 2
...
g
...
html of your React application:
3
...
Component { render() { return ( ) } } export default MyComponent � Back to Top 199
...
js? React has the following advantages over Vue
...
2
...
4
...
Easier to test
...
More information and solutions available
...
But they are helpful as base parameters
...
What is the difference between React and Angular? Let’s see the difference between React and Angular in a table format
...
e it has two-way data binding between children and parent and hence debugging is often difficult
Note: The above list of differences are purely opinionated and it vary based on the professional experience
...
� Back to Top 201
...
If the website is not using React or if React fails to communicate with DevTools then it won’t show up the tab
...
What are Styled Components? styled-components is a JavaScript library for styling React applications
...
97
� Back to Top 203
...
import React from 'react' import styled from 'styled-components' // Create a component that renders an
which is centered, red and sized at const Title = styled
...
5em; text-align: center; color: palevioletred; `
// Create a component that renders a with some padding and a papaya const Wrapper = styled
...
jsx harmony {'Lets start first styled component!'} � Back to Top 204
...
� Back to Top 205
...
1
...
i
...
You can just pass --typescript option as below
98
npx create-react-app my-app --typescript # or yarn create react-app my-app --typescript But for lower versions of react scripts, just supply --scripts-version option as react-scripts-ts while you create a new project
...
Now the project layout should look like the following: my-app/ ��
...
d
...
Does the statics object work with ES6 classes in React? No, statics only works with React
...
createClass({ statics: { someMethod: function() {
100
//
...
Component { static propTypes = { //
...
} } or writing them outside class as below, class Component extends React
...
} Component
...
} Component
...
} � Back to Top 210
...
The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more
...
� Back to Top 211
...
You should be able to use it regardless of your JavaScript build process
...
� Back to Top 212
...
const InitializeFromStateForm = reduxForm({ form: 'initializeFromState', enableReinitialize : true })(UserEdit) If your initialValues prop gets updated, your form will update too
...
How React PropTypes allow different types for one prop? You can use oneOfType() method of PropTypes
...
propTypes = { size: PropTypes
...
string, PropTypes
...
Can I import an SVG file as react component? You can import SVG directly as component instead of loading it as a file
...
0
...
“‘jsx harmony import { ReactComponent as Logo } from ‘
...
svg’ const App = () => ( {/* Logo is an actual react component */} ) “‘ Note: Don’t forget about the curly braces in the import
...
102
Why are inline ref callbacks or functions not recommended? If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element
...
class UserForm extends Component { handleSubmit = () => { console
...
input
...
handleSubmit}> type='text' ref={(input) => this
...
One quick fix is to use the ES7 class property syntax to define the function class UserForm extends Component { handleSubmit = () => { console
...
input
...
input = input } render () { return (
)
103
} } **Note:** In React v16
...
What is render hijacking in react? The concept of render hijacking is the ability to control what a component will output from another component
...
By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering
...
� Back to Top 217
...
1
...
Inheritance Inversion (II)
...
Props Proxy In this approach, the render method of the HOC returns a React Element of the type of the WrappedComponent
...
function ppHOC(WrappedComponent) { return class PP extends React
...
this
...
It is called Inheritance Inversion because instead of the WrappedComponent extending some Enhancer class, it is passively
104
extended by the Enhancer
...
function iiHOC(WrappedComponent) { return class Enhancer extends WrappedComponent { render() { return super
...
How to pass numbers to React component? You should be passing the numbers via curly braces({}) where as strings in quotes
React
...
getElementById('container � Back to Top 219
...
e
...
Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times
...
Below are the thumb rules to determine what kind of data should be put into Redux 1
...
Do you need to be able to create further derived data based on this original data? 3
...
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)? 5
...
e, use what’s in state if it’s already there instead of re-requesting it)? � Back to Top
105
220
...
The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that’s what you should know about service worker for now
...
import import import import
React from 'react'; ReactDOM from 'react-dom'; App from '
...
/registerServiceWorker';
ReactDOM
...
getElementById('root')); registerServiceWorker(); � Back to Top 221
...
Now you can do the same with function components by wrapping them in React
...
const MyComponent = React
...
What is React lazy function? The React
...
It will automatically load the bundle containing the OtherComponent when the component gets rendered
...
); } Note: React
...
If you want to do code-splitting in a server rendered app, we still recommend React Loadable
...
How to prevent unnecessary updates using setState? You can compare the current value of the state with an existing state value and decide whether to rerender the page or not
...
For example, the user profile information is conditionally rendered as follows, getUserProfile = user const latestAddress this
...
address return null; } else { return { title: } }); };
=> { = user
...
How do you render Array, Strings and Numbers in React 16 Version? Arrays: Unlike older releases, you don’t need to make sure render method return a single element in React16
...
For example, let us take the below list of developers, const ReactJSDevs = () => { return [
John
, 107
Jackie
,
Jordan
]; } You can also merge this array of items in another array component
...
render() { return 'Welcome to ReactJS questions'; } // Number render() { return 2018; } � Back to Top 225
...
You can initialize the local state without using the constructor and declare class methods by using arrow functions without the extra need to bind them
...
setState(prevState => ({ value: prevState
...
setState(prevState => ({ value: prevState
...
state
...
handleIncrement}>+
...
What are hooks? Hooks is a new feature(React 16
...
Let’s see an example of useState hook: import { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return (
You clicked {count} times
setCount(count + 1)}> Click me
); } � Back to Top
109
227
...
Call Hooks only at the top level of your react functions
...
e, You shouldn’t call Hooks inside loops, conditions, or nested functions
...
2
...
i
...
� Back to Top 228
...
You can add this plugin to your project using the below command, javascript npm install eslint-plugin-react-hooks@next And apply the below config in your ESLint config file, javascript // Your ESLint configuration { "plugins": [ //
...
"react-hooks/rules-of-hooks": "error" } } Note: This plugin is intended to use in Create React App by default
...
What are the differences between Flux and Redux? Below are the major differences between Flux and Redux Flux
Redux
State is mutable The Store contains both state and change logic There are multiple stores exist All the stores are disconnected and flat It has a singleton dispatcher React components subscribe to the store
State is immutable The Store and change logic are separate There is only one store exist Single store with hierarchical reducers There is no concept of dispatcher Container components uses connect function
110
� Back to Top 230
...
In React Router v4(version 4), the API is completely about components
...
2
...
The router module will take care history by wrapping routes with component
...
The application size is reduced by adding only the specific router module(Web, core, or native) � Back to Top 231
...
The method receives two parameters, 1
...
info: - An object with a componentStack key contains the information about which component threw the error
...
In which scenarios error boundaries do not catch errors? Below are the cases in which error boundaries doesn’t work, 1
...
Asynchronous code using setTimeout or requestAnimationFrame callbacks 3
...
When errors thrown in the error boundary code itself � Back to Top 233
...
React doesn’t need error boundaries to recover from errors in event handlers
...
So if they throw, React still knows what to display on the screen
...
Component { constructor(props) { super(props); this
...
handleClick = this
...
bind(this); } handleClick() { try { // Do something that could throw } catch (error) { this
...
state
...
} return
...
� Back to Top 234
...
For example, the try catch block used for below imperative code
112
try { showButton(); } catch (error) { //
...
� Back to Top 235
...
The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it
...
� Back to Top 236
...
You can follow either of these approaches, 1
...
2
...
� Back to Top 237
...
113
For example, BuggyCounter component displays the component stack trace as below,
Figure 8: stacktrace � Back to Top 238
...
i
...
� Back to Top 239
...
React elements: Elements that instruct React to render a DOM node
...
2
...
Portals: Render children into a different DOM subtree
...
String and numbers: Render both Strings and Numbers as text nodes in the DOM 5
...
� Back to Top 240
...
To initialize local state by assigning object to this
...
For binding event handler methods to the instance For example, the below code covers both the above cases, constructor(props) { super(props); // Don't call this
...
state = { counter: 0 }; this
...
handleClick
...
Is it mandatory to define constructor for React component? No, it is not mandatory
...
e, If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component
...
What are default props? The defaultProps are defined as a property on the component class to set the default props for the class
...
For example, let us create color default prop for the button component, class MyButton extends React
...
} MyButton
...
color is not provided then it will set the default value to ‘red’
...
e, Whenever you try to access the color prop it uses default value render() { return ; // props
...
� Back to Top 243
...
� Back to Top 244
...
It receives the error that was thrown as a parameter and should return a value to update state
...
Component { constructor(props) { super(props); this
...
return { hasError: true }; } render() { if (this
...
hasError) { // You can render any custom fallback UI return
Something went wrong
...
props
...
What is the methods order when component re-rendered? An update can be caused by changes to props or state
...
116
1
...
3
...
5
...
What are the methods invoked during error handling? Below methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component
...
static getDerivedStateFromError() 2
...
What is the purpose of displayName class property? The displayName string is used in debugging messages
...
context; /*
...
context; /* render something based on the value of MyContext */ } } MyClass
...
Static field You can use a static class field to initialize your contextType using public class field syntax
...
Component { static contextType = MyContext; render() { let value = this
...
What is a consumer? A Consumer is a React component that subscribes to context changes
...
The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree
...
Consumer> {value => /* render something based on the context value */ }
...
How do you solve performance corner cases while using context? The context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders
...
class App extends React
...
Component { constructor(props) { super(props); this
...
state
...
What is the purpose of forward ref in HOCs? Refs will not get passed through because ref is not a prop
...
If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component
...
For example, we can explicitly forward refs to the inner FancyButton component using the React
...
The below HOC logs all props, function logProps(Component) { class LogProps extends React
...
log('old props:', prevProps); console
...
props); } render() { const {forwardedRef,
...
props; // Assign the custom prop "forwardedRef" as a ref return
...
forwardRef((props, ref) => { 135
return
...
Component { focus() { //
...
} export default logProps(FancyButton); Now let’s create a ref and pass it to FancyButton component
...
import FancyButton from '
...
createRef(); ref
...
focus(); label="Click Me" handleClick={handleClick} ref={ref} />; � Back to Top 283
...
The second ref argument only exists when you define a component with React
...
� Back to Top 284
...
This is because your library likely has a different behavior such as what
136
refs get assigned to, and what types are exported
...
� Back to Top 285
...
For default props, you need to define getDefaultProps() as a function on the passed object
...
var Greeting = createReactClass({ getDefaultProps: function() { return { name: 'Jhohn' }; }, getInitialState: function() { return {message: this
...
message}; }, handleClick: function() { console
...
state
...
props
...
i
...
bind(this) with in constructor for event handlers
...
Is it possible to use react without JSX? Yes, JSX is not mandatory for using React
...
Each JSX element is just syntactic sugar for calling React
...
children)
...
Component { render() {
137
return
Hello {this
...
message}
; } } ReactDOM
...
getElementById('root') ); You can write the same code without JSX as below, class Greeting extends React
...
createElement('div', null, `Hello ${this
...
message}`); } } ReactDOM
...
createElement(Greeting, {message: 'World'}, null), document
...
What is diffing algorithm? React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree
...
However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree
...
This is far too expensive
...
Two elements of different types will produce different trees
...
The developer can hint at which child elements may be stable across different renders with a key prop
...
What are the rules covered by diffing algorithm? When diffing two trees, React first compares the two root elements
...
It covers
138
the below rules during reconciliation algorithm, 1
...
For example, elements to , or from to of different types lead a full rebuild
...
DOM Elements Of The Same Type: When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes
...
Component Elements Of The Same Type: When a component updates, the instance stays the same, so that state is maintained across renders
...
After that, the render() method is called and the diff algorithm recurses on the previous result and the new result
...
Recursing On Children: when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference
...
first
second
first
second
third
5
...
When children have keys, React uses the key to match children in the original tree with children in the subsequent tree
...
When do you need to use refs? There are few use cases to go for refs, 1
...
2
...
3
...
� Back to Top 290
...
i
...
Lets take an example with the children prop for render props, (
The mouse position is {mouse
...
y}
)}/> Actually children prop doesn’t need to be named in the list of “attributes” in JSX element
...
x}, {mouse
...
Mouse
...
func
...
What are the problems of using render props with pure components? If you create a function inside a render method, it negates the purpose of pure component
...
You can solve this issue by defining the render function as instance method
...
How do you create HOC using render props? You can implement most higher-order components (HOC) using a regular component with a render prop
...
function withMouse(Component) { return class extends React
...
this
...
� Back to Top 293
...
If your application renders long lists of data then this technique is recommended
...
� Back to Top 294
...
If you still want to display them then you need to convert it to string
...
� Back to Top 295
...
g
...
For example, dialogs, global message notifications, hovercards, and tooltips
...
How do you set default value for uncontrolled component? In React, the value attribute on form elements will override the value in the DOM
...
To handle this case, you can specify a defaultValue attribute instead of value
...
handleSubmit}>